class Solution(object):
    def kMirror(self, k, n):
        c = 0
        ans = 0
        wei = 1
        base = 1
        max_range = 10
        def judge(num):
            st = []
            while num > 0:
                st.append(num % k)
                num = num // k
            return st == st[::-1]
        print(judge(9470749))
        while c < n:
            if base < max_range:
                s = str(base)
                if wei % 2 == 1:
                    new_num = int(s[:-1] + s[-1] + s[-2::-1])
                else:
                    new_num = int(s + s[::-1])
                if judge(new_num):
                    c += 1
                    ans += new_num
                base += 1
            else:
                wei += 1
                base = 10 ** ((wei - 1) // 2)
                max_range = 10 ** ((wei + 1) // 2)
        
        return ans





data = Solution()
k = 7
n = 17
print(data.kMirror(k, n))